import * as THREE from "three";
import { CSS3DRenderer, CSS3DObject } from 'three/addons/renderers/CSS3DRenderer.js';
import scene from "../scene";
import dataList from '../data/index.json'
import mitt from "@/utils/mitt";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader"
import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { FontLoader } from 'three/addons/loaders/FontLoader.js';
import controls from '../controls'
import gsap from "gsap";
class Monitor {
  zebraCrossingOBJ = []
  pedalOBJ = []
  EnterImgOBJ = []
  constructor(options) {
    mitt.on('time', (time) => {
      this.zebraCrossingOBJ.forEach(item => {
        item.material.uniforms.time.value = time
      })
    })
  }
  create () {
    this.renderer = new CSS3DRenderer();
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    document.querySelector('#monitor').appendChild(this.renderer.domElement);
    this.loader = new GLTFLoader();
    // 实例化draco载入库
    this.dracoLoader = new DRACOLoader();
    // 添加draco载入库
    this.dracoLoader.setDecoderPath("./draco/");
    // 添加draco载入库
    this.loader.setDRACOLoader(this.dracoLoader);
    dataList.forEach((item, index) => {
      this.add(index, item)
    });
  }

  add (index, item) {
    let right = 10 * (index % 5)
    let top = 20 * (Math.floor(index / 5))
    // const element = document.createElement('div');
    // element.classList.add('monitor-card')
    // const objectCSS = new CSS3DObject(element);
    this.loader.load("./model/显示器.glb", (gltf) => {
      const texture = new THREE.TextureLoader().load(item.img, (e) => {
      })
      console.log(texture)
      texture.wrapS = THREE.RepeatWrapping;
      texture.wrapT = THREE.RepeatWrapping;
      texture.repeat.set(4, 4)
      texture.rotation = -Math.PI / 2
      console.log(gltf.scene.children[3])
      // 创建材质并应用纹理
      var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true, map: texture });
      //   const material = new THREE.ShaderMaterial({
      //     side: THREE.DoubleSide,
      //     transparent: true,
      //     uniforms: {
      //       time: { value: 1.0 },
      //       texture1: { value: texture }
      //     },
      //     //顶点着色器
      //     vertexShader: `
      // varying vec2 vUv;
      //         void main(){
      //         vUv=uv;
      //             gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4( position, 1.0 ) ;
      //         }
      //     `,
      //     //片元着色器
      //     fragmentShader: `
      // varying vec2 vUv;
      // uniform sampler2D texture1; // 纹理贴图变量
      //         void main(){
      //              // 计算旋转后的UV坐标
      //         float angle = -90.0 * 3.14159 / 180.0; // 将角度转换为弧度
      //         float s = sin(angle);
      //         float c = cos(angle);
      //         mat2 rotationMatrix = mat2(c, -s, s, c);
      //         vec2 rotatedUV = rotationMatrix * vUv*5.0;
      //          gl_FragColor = texture2D(texture1, rotatedUV); // 使用纹理贴图
      //         }
      //   `

      //   });

      const xsq = gltf.scene
      xsq.children[3].material = material
      xsq.children[3].rotateY(Math.PI)

      xsq.position.set(20 + right, 0.5, -20 - top)
      scene.add(xsq);
      this.zebraCrossing(xsq.position, item)
      this.pedal(xsq.position, item)
      this.text(xsq.position, item)
      this.EnterImg(xsq.position, item)
    })


  }
  //斑马线边框
  zebraCrossing (position, item) {
    const geometry = new THREE.CylinderGeometry(2.7, 2.7, 0.5, 4, 1, true);
    const material = new THREE.ShaderMaterial({
      //内置的uniforms和attributes的定义会自动添加到GLSL shader代码中
      side: THREE.DoubleSide,
      transparent: true,
      uniforms: {
        time: { value: 1.0 },
      },
      //顶点着色器
      vertexShader: `
      varying vec2 vUv;
              void main(){
              vUv=uv;
                  gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4( position, 1.0 ) ;
              }
          `,
      //片元着色器
      fragmentShader: `
      varying vec2 vUv;
      uniform float time;
              void main(){

            // 计算纹理移动的偏移量
            float speed = 0.1; // 移动速度
            float offset = sin(time * speed);

            // 计算旋转后的UV坐标
            float angle = 3.0 * 3.14159 / 180.0; // 将角度转换为弧度
            float s = sin(angle);
            float c = cos(angle);
            mat2 rotationMatrix = mat2(c, -s, s, c);
            vec2 rotatedUV = rotationMatrix * vUv;

            // 添加纹理移动效果
            rotatedUV.x += offset;

            // 判断是否在圆柱的上下边缘
            float borderSize = 0.1; // 边缘宽度
            if (rotatedUV.y < borderSize || rotatedUV.y > 1.0 - borderSize) {
                gl_FragColor = vec4(1.0, 1.0, 1.0, 0.6); // 白色
            } else if (fract(rotatedUV.x * 20.0) < 0.5) {
                gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1); // 黑色
            } else {
                gl_FragColor = vec4(1.0, 1.0, 1.0, 0.3); // 白色
            }
              }
        `

    });
    const cube = new THREE.Mesh(geometry, material);
    cube.name = `边框-${item.id}`
    this.zebraCrossingOBJ.push(cube)
    cube.position.set(position.x, 3 - 3.9, position.z + 8)
    cube.rotateY(Math.PI / 4)
    scene.add(cube);
  }
  //踏板 打开文章的踏板
  pedal (position, item) {
    const geometry = new THREE.PlaneGeometry(4, 4);
    // 创建一个包含文本的Canvas元素
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    // context.rotate(Math.PI / 2); // 旋转90度
    context.font = 'Bold 40px Arial';
    context.fillStyle = 'white';
    context.fillText('进 入', 100, 90);
    // 创建一个CanvasTexture
    var texture = new THREE.CanvasTexture(canvas);
    const material = new THREE.ShaderMaterial({
      //内置的uniforms和attributes的定义会自动添加到GLSL shader代码中
      side: THREE.DoubleSide,
      transparent: true,
      uniforms: {
        time: { value: 1.0 },
        texture1: { value: texture }
      },
      //顶点着色器
      vertexShader: `
  varying vec2 vUv;
          void main(){
          vUv=uv;
              gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4( position, 1.0 ) ;
          }
      `,
      //片元着色器
      fragmentShader: `
  varying vec2 vUv;
  uniform sampler2D texture1; // 纹理贴图变量
          void main(){
        // 判断是否在圆柱的上下边缘
        float borderSize = 0.04; // 边缘宽度
        if (vUv.y < borderSize || vUv.y > 1.0 - borderSize ||vUv.x < borderSize || vUv.x > 1.0 - borderSize ) {
            gl_FragColor = vec4(1.0, 1.0, 1.0, 0.5); // 白色
        } else  {
            // gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1); // 黑色
           gl_FragColor = texture2D(texture1, vUv); // 使用纹理贴图
        }
          }
    `

    });
    const cube = new THREE.Mesh(geometry, material);
    cube.name = `平面-${item.id}`
    cube.rotation.set(-Math.PI / 2, 0, 0)
    cube.position.set(position.x, 3 - 3, position.z + 8)
    this.pedalOBJ.push(cube)
    scene.add(cube);
  }
  //文字 打开
  text (position, item) {
    // 创建一个平面几何体
    const loader = new FontLoader();
    loader.load('./fonts/汉仪洛神行.json', function (font) {
      const geometry = new TextGeometry(item.title, {
        font: font,
        size: 0.5,
        depth: 0.06,
        curveSegments: 12,
        bevelEnabled: false,
        bevelThickness: 1,
        bevelSize: 1,
        bevelSegments: 1
      });
      // 创建一个材质
      var material = new THREE.MeshBasicMaterial({ transparent: true, color: 0xe4f9f5 });
      // 创建一个文本网格
      var mesh = new THREE.Mesh(geometry, material);
      mesh.rotation.set(-Math.PI / 2, 0, 0)
      mesh.position.set(position.x - 2, 3 - 3, position.z + 2)
      scene.add(mesh);
    });
    loader.load('./fonts/汉仪洛神行.json', function (font) {
      for (var i = 0; i <= item.content.length; i += 20) {
        const geometry = new TextGeometry(item.content.substring(i, i + 20), {
          font: font,
          size: 0.3,
          depth: 0.02,
          curveSegments: 12,
          bevelEnabled: false,
          bevelThickness: 1,
          bevelSize: 1,
          bevelSegments: 1
        });
        // 创建一个材质
        var material = new THREE.MeshBasicMaterial({ transparent: true, color: 0xe4f9f5 });
        // 创建一个文本网格
        var mesh = new THREE.Mesh(geometry, material);
        mesh.rotation.set(-Math.PI / 2, 0, 0)
        mesh.position.set(position.x - 2, 3 - 3, position.z + 3 + Math.floor(i / 20))
        scene.add(mesh);
      }
    });





    // mesh.rotation.set(-Math.PI / 2, 0, 0)
    // scene.add(mesh);
  }
  EnterImg (position, item) {
    const element = document.createElement('div');
    element.classList.add('monitor-enter')
    const objectCSS = new CSS3DObject(element);
    objectCSS.name = `enter-${item.id}`
    objectCSS.position.set(position.x, -2, position.z + 8)
    objectCSS.visible = false
    this.EnterImgOBJ.push(objectCSS)
    scene.add(objectCSS);
  }
}
export default new Monitor()